import os, time
from flask import current_app

from models.weibo_info import WeiboInfo

from spider.weibo_spider import get_weibo_list_by_page, get_user_weibo_page

from database.weibo_repo import select_weibo_by_weibo_id, insert_weibo, update_weibo, select_weibo_by_update_time, select_weibo_by_date

from utils.date_format import get_last_month_date, is_over_one_day
from utils.print_message import print_message

# 获取单页微博数据
def weibo_info_service_by_page(user_id, cookie, page):
    result = []
    start_date = get_last_month_date()
    data = get_weibo_list_by_page(user_id, cookie, page, start_date)
    # 1.先判断数据库中是否已经存在该微博
    for item in data:
        weibo_id = item['weibo_id']
        res = select_weibo_by_weibo_id(weibo_id)
        # 1.1 数据库有这条微博且在有效时间内，则跳过
        if res and not is_over_one_day(res['update_time']):
            weibo_class = WeiboInfo(**item)
            result.append(weibo_class.json())
            continue
        weibo_class = WeiboInfo(**item)
        # 1.2 没有这条微博则插入
        if not res:
            insert_weibo(weibo_class)
        # 1.3 更新
        else:
            update_weibo(weibo_class)
        result.append(weibo_class.json())
    return result

# 获取近一个月的微博数据
def weibo_info_month_ago_service(user_id, cookie, limit = 20):
    # 获取最近更新的一条微博,如果为一天以内，则不需要爬数据了
    current_update_data_list = select_weibo_by_update_time(user_id, limit = 1)
    if current_update_data_list and not is_over_one_day(current_update_data_list[0]['update_time']):
        result = select_weibo_by_update_time(user_id, limit)
        for i in range(len(result)):
            result[i] = WeiboInfo(**result[i]).json()
        return result
    
    start_date = get_last_month_date()
    result = []
    # 1.获取页数
    total_page = get_user_weibo_page(user_id, cookie, start_date)
    # 2.遍历每一页
    for page in range(1, total_page + 1):
        data = weibo_info_service_by_page(user_id, cookie, page)
        if len(data) == 0:
            break
        result += data
        time.sleep(0.5)
        # 最多爬6页
        if page > 5:
            break
        
    return result[:limit]

def upload_weibo_info_list_service(data):
    # 1.先判断数据库中是否已经存在该微博
    for item in data:
        weibo_id = item['weibo_id']
        res = select_weibo_by_weibo_id(weibo_id)
        # 1.1 数据库有这条微博且在有效时间内，则跳过
        if res and not is_over_one_day(res['update_time']):
            continue
        weibo_class = WeiboInfo(**item)
        # 1.2 没有这条微博则插入
        if not res:
            insert_weibo(weibo_class)
        # 1.3 更新
        else:
            update_weibo(weibo_class)
    return {'finished': True}
        